var editObj=null,ptable=null,treeGrid=null,tableId='treeTable',layer=null;
layui.use(['form','tree','element','table','laytpl','treeGrid','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var treeGrid = layui.treeGrid;//很重要

    //获取当前场景信息
    var _ticket = $.cookie("token");
    if(_ticket != null && _ticket !== ""){
        $.ajax({
            url : "http://localhost:8083/user/token/" + _ticket,//单点登录链接
            dataType : "jsonp",
            type : "GET",
            success : function(data){
                if (data.code == 200) {
                    var user = data.data.user;

                    var option = {
                        id:tableId
                        ,elem: '#'+tableId
                        ,url:'/scene/list?user=' + user.id
                        ,cellMinWidth: 100
                        ,idField:'id'//必須字段
                        ,treeId:'id'//树形id字段名称
                        ,treeUpId:'parentId'//树形父id字段名称
                        ,treeShowName:'name'//以树形式显示的字段
                        ,heightRemove:[".dHead",10]//不计算的高度,表格设定的是固定高度，此项不生效
                        ,height:'full-100'
                        ,isFilter:false
                        ,iconOpen:true//是否显示图标【默认显示】
                        ,isOpenDefault:true//节点默认是展开还是折叠【默认展开】
                        ,loading:true
                        ,method:'post'
                        ,limit : 20
                        ,isPage:false
                        ,cols: [[
                            {type:'numbers'}
                            ,{type:'checkbox',sort:true}
                            ,{field:'name', width:200, title: '名称'}
                            ,{field:'typeId', title: '场景类型',templet: function(d){
                                    var categoryName = "";
                                    $.ajax({
                                        url : '/scene/type/' + d.typeId,
                                        async:false,
                                        success: function (data) {
                                            categoryName = data.name;
                                        }
                                    });
                                    return categoryName == null?'':categoryName;
                                }}
                            ,{field:'areaId', title: '所属地区',templet: function(d){
                                    var areaName = "";
                                    $.ajax({
                                        url : '/area/' + d.areaId,
                                        async:false,
                                        success: function (data) {
                                            areaName = data.name;
                                        }
                                    });
                                    return areaName == null?'':areaName;
                                }}
                            ,{field:'address', title: '详细地址信息'}
                            ,{field:'sort', title: '排序值'}
                            ,{field:'remarks', title: '备注'}
                            ,{field: 'createDate', minWidth:120, title: '添加时间', sort: true,align:'center',templet:function(d){
                                    //处理时间
                                    var date = new Date(d.createDate);
                                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                                }}
                            ,{Width:100,title: '操作', align:'center'
                                ,templet: function(d){
                                    var html='';
                                    var addBtn='<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>';
                                    var delBtn='<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>';
                                    return addBtn+delBtn;
                                }
                            }
                        ]]
                        ,parseData:function (res) {//数据加载后回调
                            return res;
                        }
                        ,onClickRow:function (index, o) {
                            /*console.log(index,o,"单击！");*/
                        }
                        ,onDblClickRow:function (index, o) {
                            /*console.log(index,o,"双击");*/
                        }
                    };

                    //场景列表
                    ptable=treeGrid.render(option);

                    treeGrid.on('tool('+tableId+')',function (obj) {
                        if(obj.event === 'del'){//删除行
                            del(obj);
                        }else if(obj.event==="edit"){//添加行
                            var index = layui.layer.open({
                                title : "修改场景信息",
                                type : 2,
                                content : "sceneryEdit?id=" + obj.data.id,
                                area: ['100%',$(document).height() + 'px'],
                                success : function(){
                                    setTimeout(function(){
                                        layui.layer.tips('点击此处返回场景信息列表', '.layui-layer-setwin .layui-layer-close', {
                                            tips: 3
                                        });
                                    },500);
                                }
                            });
                            layui.layer.full(index);
                            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
                            $(window).on("resize",function(){
                                layui.layer.full(index);
                            });
                        }
                    });

                    //查询
                    $(".search_btn").on("click",function(){
                        var searchKey = $(".searchVal").val();
                        if(searchKey != ''){
                            option.url = '/scene/query';
                            option.where = {name: searchKey};
                            treeGrid.render(option);
                        }else{
                            layer.msg("请输入搜索的内容");
                        }
                    });

                    //批量删除
                    $(".delAll_btn").click(function(){
                        var checkStatus = treeGrid.checkStatus(tableId),
                            data = checkStatus.data,
                            idArr = [];
                        if(data.length > 0) {
                            for (var i in data) {
                                idArr.push(data[i].id);
                            }
                            layer.confirm('确定删除选中的场景记录？', {icon: 3, title: '提示信息'}, function (index) {
                                for(var i=0;i<idArr.length;i++){
                                    $.get("/scene/delete?id=" + idArr[i],function(data){
                                        if (data.code == 200) {
                                            layer.msg("删除成功！");
                                        } else {
                                            layer.msg("删除失败，请重试！");
                                        }
                                        ptable.reload();
                                        layer.close(index);
                                    });
                                }
                            })
                        }else{
                            layer.msg("请选择需要删除的场景");
                        }
                    });

                    //添加顶级场景数据
                    $(".addBtn").click(function(){
                        var index = layui.layer.open({
                            title : "添加场景数据",
                            type : 2,
                            content : "sceneryAdd",
                            area: ['100%',$(document).height() + 'px'],
                            success : function(layero, index){
                                var body = layui.layer.getChildFrame('body', index);
                                setTimeout(function(){
                                    layui.layer.tips('点击此处返回场景列表', '.layui-layer-setwin .layui-layer-close', {
                                        tips: 3
                                    });
                                },500)
                            }
                        });
                        layui.layer.full(index);
                        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
                        $(window).on("resize",function(){
                            layui.layer.full(index);
                        });
                    });

                    function del(obj) {
                        layer.confirm("你确定删除数据吗？如果存在下级节点则一并删除", {icon: 3, title:'提示'},
                            function(index){//确定回调
                                layer.close(index);
                                $.get("/scene/delete?id=" + obj.data.id,function(data){
                                    if (data.code == 200) {
                                        layer.msg("删除成功！");
                                    } else {
                                        layer.msg("删除失败，请重试！");
                                    }
                                    ptable.reload();
                                    layer.close(index);
                                });
                            },function (index) {//取消回调
                                layer.close(index);
                            }
                        );
                    }

                } else {
                    layer.confirm('用户登录已过期，请中重新登录', {icon: 3, title: '提示信息'}, function (tips) {window.location.href = "http://localhost:8083/login";});
                    window.location.href = "http://localhost:8083/login";
                }
            }
        });
    } else {
        layer.confirm('用户登录已过期，请中重新登录', {icon: 3, title: '提示信息'}, function (tips) {window.location.href = "http://localhost:8083/login";});
        window.location.href = "http://localhost:8083/login";
    }

    /*//场景分类数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调

        },
        nodes:null
    };
    //异步加载场景分类数据
    $.get('/scene/type/tree',function(data) {
        treeData.nodes = data.data;
        layui.tree(treeData);
    });*/




});